const db = wx.cloud.database();
const _ = db.command;
const app = getApp();
Page({
  data: {
    radio1: 0,
    radio2: 0,
    radio3: 0,
    questions: [],
    adminId: '',
    userId: app.globalData.userInfo.id,
  },
  onLoad(options) {
    const that = this;
    const id = options.id;
    this.setData({
      adminId: id,
    })
    db.collection('Management_user').where({
      _id: _.eq(id),
    }).get().then(res => {
      if (res.data.length === 1) {
        const questions = res.data[0].questions;
        const selects = res.data[0].selects;
        that.setData({
          questions: questions.map((item, index) => {
            return {
              question: item,
              selects: selects[index]
            }
          })
        })
      }
    })
  },
  onChangeRadio0(e) {
    // console.log(e.detail, 1)
    this.setData({
      radio1: e.detail
    })
  },
  onChangeRadio1(e) {
    // console.log(e.detail, 2)
    this.setData({
      radio2: e.detail
    })
  },
  onChangeRadio2(e) {
    // console.log(e.detail, 3)
    this.setData({
      radio3: e.detail
    })
  },
  onSubmit(e) {
    // 用户绑定管理员
    const {
      userId,
      adminId,
      radio1,
      radio2,
      radio3
    } = this.data;
    db.collection('Management_user').doc(userId).update({
      data: {
        selectAdmin: adminId,
        selectAnswer: [radio1, radio2, radio3],
      }
    })
    // 管理员绑定用户
    db.collection('Management_user').doc(adminId).update({
      data: {
        userList: _.push(userId),
      }
    })
    wx.showToast({
      title: '绑定管理员成功！',
    });
    const userInfo = app.globalData.userInfo;
    userInfo.selectAdmin = adminId;
    wx.setStorageSync('userInfo', userInfo);
    wx.reLaunch({
      url: "/pages/index/index",
    });
  }
})